<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Exports\OnTheJobExport;
use App\Exports\OrderDetailExports;
use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Miniprograme\SubscribeController;
use App\Models\Car;
use App\Models\Order\SendOrReturnCarTime;
use App\Models\Order\Entrymanage;
use Modules\Manager\Entities\Manager;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\ChangeSeries;
use Modules\Car\Entities\RecognizeDrivingLicense;
use App\Http\Controllers\Wx\SendTemplateController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use App\Models\Car\ExternalTransfer;
class OrderController extends Controller
{
    use ResponseData,NewBaseData,PayTrait;

    //订单列表
    public function list(CarOrder $order,Request $request){
        $phone = $request->input('phone','');
        $size = $request->input('size',10);
        $page = $request->page-1;
        $data = $order->with(['car','user','changeCar'])
            ->when($phone,function($query)use($phone){
                $query->where('phone',$phone);
            })
            ->orderByDesc('id')
            ->get();
        $others = $order->with('car','user')
            ->when($phone,function($query)use($phone){
                $query->where('phone',$phone);
            })
            ->orderByDesc('id')
            ->get();
        if($others) {
            foreach ($others as $item) {
                $data->push($item);
            }
        }
        $slice = $data->slice($page*$size, $size);
        $res['current_page'] = $page+1;
        $res['total'] = $data->count();
        $last =  array();
        foreach ($slice as $value){
            $last[] = $value;
        }
        $res['data'] = $last;
        return $this->success($res);
    }

    public function update(Request $request){
        $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
        if($order){
            if($request->status==-4&&$order->status==2){
                $total = $order->mini_pay*100;
                if($order->mini_pay<$order->total){
                    $this->miniRefund($order->order_sn,$order->out_trade_no,$total,$total);
                    return $this->success('退款成功!');
                }else{
                    return $this->failed('退款失败,请联系管理员',201);
                }

            }
            if($request->status==-4&&$order->status>2){
                return $this->failed('已经进入送车状态，请联系管理员退款',201);
            }

            $map = $this->chooseStatus($request,$order);
            $order->update($map);
            return $this->success('修改成功');

        }else{
            return $this->failed('订单不存在',201);
        }

    }
    protected function isSetCar($id){
        return CarOrder::query()->find($id);
    }
    public function chooseStatus($request,$data){

        $map = $request->all();
        switch ($request->status)
        {
            case 2:
                $map['send_car_time'] = now();
                (new SubscribeController())->send_template($data);
                break;
            case 3:
                $map['fetch_time'] = now();
                (new SubscribeController())->send_arrive($data);
                break;
            case -1:
                if($data->status==0){
                    $map['status']= -1;
                }
                $map['updated_at'] = now();
                break;
            case -4:
                $map['status']= -4;
                $this->refund($data);
                break;
            case 6:
                $map['return_time'] = now();
                $this->diffDays($data->pre_fetch_time,now());
                $map['lease_days'] = $this->daily;
                $map['fetch_hours'] = $this->hours;
                $map['return_position'] = $request->return_position?:null;
                $map['status'] = 6;
                //释放车辆
                // RecognizeDrivingLicense::query()
                //     ->where('id',$data->gear_car_id)
                //     ->update(['is_used'=>0]);
                break;
        }
        return $map;
    }
    //小程序接口
    public function all(Request  $request){

        if($request->status==Constant::ORDER_All){
            $model = CarOrder::query()
                ->where('openid',$request->openid);
        }else{
            $model = CarOrder::query()
                ->where('openid',$request->openid)
                ->where('status',$request->status);
        }
        if($request->filled('search')){
            $model->where('phone',$request->search)
                ->orWhere('wx_name',$request->search)
                ->orWhere('nickname',$request->search)
                ->orWhere('nickname',$request->search)
                ->orWhere('customer_name',$request->search)
                ->orWhere('gear_car_name',$request->search)
                ->orWhere('gear_car_name',$request->search)
                ->orWhere('plate_number',$request->search);
        }
        $size = $request->input('size',10);
        $data = $model->orderBy('id','desc')
            ->simplePaginate($size);
        return $this->success($data);
    }
    public function orderDetail(Request $request){
        if ($request->filled('id')) {
            $data = CarOrder::with('service','car','user','gear','customer','initCar','wxCustomer','phoneCustomer', 'orderPrePays', 'maintenance', 'illegals', 'renewLease', 'contracts', 'orderEvidence')->where('id',$request->id)->first();
        } elseif ($request->filled('order_sn')) {
            $data = CarOrder::with('service','car','user','gear','customer','initCar','wxCustomer','phoneCustomer', 'orderPrePays', 'maintenance', 'illegals', 'renewLease', 'contracts', 'orderEvidence')->where('order_sn',$request->order_sn)->first();
        }
        if ($data->fetch_hours<0) {
            $data->fetch_hours=0;
        }
        if ($data->platform_fact_pay==='0.00') {
            $data->platform_fact_pay='';
        }
        if($data['plate_number']==''&&!empty($data['gear_car_id'])) {
            info('更新订单里的车牌号'.$data['gear']->plate_number);
            // 如果当前订单无车牌号，需要更新进去
            CarOrder::query()->where('id',$request->id)->update(['plate_number'=>$data['gear']->plate_number]);
        }
        return $this->success($data);
    }
    //订单退款
    public function refund($order){
            $data = [
                'type' => 'miniapp',
                'out_trade_no' => $order->out_trade_no,
                'out_refund_no' => time(),
                'total_fee' => $order->bc_total*100,
                'refund_fee' => $order->bc_total*100,
                'refund_desc' => '全额退款',
                'notify_url' => 'https://zc.ywbtzc.com/api/pay/refund',
            ];
            return $this->WxPay()->refund($data);
    }
    //更换车辆id
    public function changeCarSeries(CarOrder $order,Request $request){
        $order = $order->with('initCar')->find($request->order_id);
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        $order->is_change_status  = Constant::CHANGE_WAITTING;
        $order->change_car_series_id = $request->series_id;
        $res = $order->save();
        if($res){
            $user = $request->user();
            $data['order_id'] = $order->id;
            $data['order_sn'] = $order->order_sn;
            $data['manager'] = $user->name?:'';
            $data['manager_id'] = $user->id;
            $data['old'] = $order->car_series_id;
            $data['new'] = $request->series_id;
            ChangeSeries::query()->create($data);
            // 改排通知功能取消了，此处注释掉
            // if($order->openid){
            //     $old = $this->getCarName($order->car_series_id);
            //     $new = $this->getCarName($order->series_id);
            //     $content = "点击查看订单详情>>>";
            //     (new SubscribeController())->ChangeCarNotify($order,$old,$new,$content);
            // }
        }
        return $this->success(true);
    }
    protected function getCarName($id){
        return Car::query()->wehre('id',$id)->value('name');
    }
    //更新 送车状态和还车状态
    public function updateProcessStatus(CarOrder $model,Request $request){
        $order = $model->find($request->order_id);
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        if($request->process_status==2){
            $order->send_employer_id= $request->send_employer_id;
            $order->send_employer_nickname= $request->send_employer_nickname;
            $order->verify_at = $request->verify_at;//送达时间
        }
        $send_or_fetch = [
          'order_sn'=>$order->order_sn,
            'car_id'=>$order->gear_car_id,
            'type'=>$request->process_status,
        ];
        SendOrReturnCarTime::query()->create($send_or_fetch);
        $order->process_status = $request->process_status;
        $order->save();
        return $this->success('更新成功');
    }
    //获取待排车数据
    public function getProcessRow(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
            $model = $model
                ->where('department',$user->department_id)
                ->where('status',$request->status);

        }else{
            $model = $model
                ->where('status',$request->status);
        }
        $data = $model->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }
    //获取待签署数据
    public function getProcessSign(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
            $model = $model
                ->where('department',$user->department_id)
                ->where('status',5)
                ->whereIn('is_sign_contract',[1,2]);

        }else{
            $model = $model
                ->where('status',5)
                ->whereIn('is_sign_contract',[1,2]);
        }
        $data = $model->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }
    //获取用车中数据
    public function getProcessUsedcar(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
            $model = $model
                ->where('department',$user->department_id)
                ->where('status',5)
                ->where('is_sign_contract',$request->is_sign_contract)
                ->where('is_send_return_order',$request->is_send_return_order);

        }else{
            $model = $model
                ->where('is_sign_contract',$request->is_sign_contract)
                ->where('status',5)
                ->where('is_send_return_order',$request->is_send_return_order);
        }
        $data = $model->orderBy('pre_return_time','asc')->paginate($size);
        return $this->success($data);
    }
    //获取取回中数据
    public function getProcessReturningcar(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
            $model = $model
                ->where('department',$user->department_id)
                ->where('status',5)
                ->where('return_employer_id','!=',0);

        }else{
            $model = $model
                ->where('status',5)
                ->where('return_employer_id','!=',0);
        }
        $data = $model->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }
    //获取取回中数据
    public function getProcessReturncar(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
            $model = $model
                ->where('department',$user->department_id)
                ->where('status',5)
                ->where('is_send_return_order',2)
                ->where('is_sign_contract',3)
                ->where('return_employer_id',0);

        }else{
            $model = $model
                ->where('status',5)
                ->where('is_send_return_order',2)
                ->where('is_sign_contract',3)
                ->where('return_employer_id',0);
        }
        $data = $model->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }
    //获取车辆出车和还车状态数据
    public function getProcessStatus(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        if($user->post_id==2){
            $model = $model
                ->where('department',$user->department_id)
                ->where('process_status',$request->process_status);

        }else{
            $model = $model
                ->where('process_status',$request->process_status);
        }
        $model = $model->where('status','>',0);
        if($request->process_status==2){
            $data = $model->orderBy('is_send_return_order','desc')->orderBy('pre_return_time','asc')
                ->paginate($size);
        }else{
            $data = $model->orderBy('is_send_return_order','desc')->orderBy('id', 'desc')
                ->paginate($size);
        }
        return $this->success($data);
    }
    //获取送取车清洗列表：1待送车、2待取车、3待清洗
    public function getSqcStatus(CarOrder $order,Request $request){
        $user = $request->user();
        $size = $request->input('size',10);
        $model = $this->searchOrderModel($request);
        $model = $model->where('status','>',0);
        if($request->status==1){
            $model = $model->where('is_send_order',2)->where(function($query)use($user){
                return $query->where('process_status',1)->orWhere('status',3);
            })->where(function($query)use($user){
                return $query->where('send_employer_id',0)->orWhere('send_employer_id',$user->id);
            });
            $data = $model->orderBy('send_employer_id','desc')->orderBy('pre_fetch_time','asc')->paginate($size);
        }elseif($request->status==2){
            $model = $model->where('is_send_return_order',2)->where('process_status',2)->where(function($query)use($user){
                return $query->where('return_employer_id',0)->orWhere('return_employer_id',$user->id);
            });
            // $model = $model->where('is_send_return_order',2)->where('return_employer_id',0);
            $data = $model->orderBy('return_employer_id','desc')->orderBy('pre_return_time','asc')->paginate($size);
        }elseif($request->status==3){
            // $model = $model->where('is_send_clear_order',2)->where('return_employer_id',$user->id)->where('clieaner_id',0)->where('clieaner_can_time','>',now());
            $model = $model->where('is_send_clear_order',2)->where('clieaner_id',0)->where('clieaner_can_time','>',now());
            $data = $model->orderBy('pre_return_time','asc')->paginate($size);
        }elseif($request->status==4){
            $model = $model->where('status',5)->whereIn('is_sign_contract',[1,2])->where(function($query)use($user){
                return $query->where('send_employer_id',0)->orWhere('send_employer_id',$user->id);
            });
            // $model = $model->where('is_send_return_order',2)->where('return_employer_id',0);
            $data = $model->orderBy('is_sign_contract','desc')->orderBy('pre_return_time','asc')->paginate($size);
        }
        $dsc = CarOrder::query()->where('status','>',0)->where('is_send_order',2)->where(function($query)use($user){
            return $query->where('process_status',1)->orWhere('status',3);
        })->where(function($query)use($user){
            return $query->where('send_employer_id',0)->orWhere('send_employer_id',$user->id);
        })->count();
        $dqs = CarOrder::query()->where('status',5)->whereIn('is_sign_contract',[1,2])->where(function($query)use($user){
            return $query->where('send_employer_id',0)->orWhere('send_employer_id',$user->id);
        })->count();
        $dqc = CarOrder::query()->where('status','>',0)->where('is_send_return_order',2)->where('process_status',2)->where(function($query)use($user){
            return $query->where('return_employer_id',0)->orWhere('return_employer_id',$user->id);
        })->count();
        // $dqc = CarOrder::query()->where('status','>',0)->where('is_send_return_order',2)->where('return_employer_id',0)->count();
        // $dqx = CarOrder::query()->where('status','>',0)->where('is_send_clear_order',2)->where('clieaner_id',0)->where('return_employer_id',$user->id)->where('clieaner_can_time','>',now())->count();
        $dqx = CarOrder::query()->where('status','>',0)->where('is_send_clear_order',2)->where('clieaner_id',0)->where('clieaner_can_time','>',now())->count();
        // 外调车数据
        if($request->status==4){
            $datawd = [];
        }else{
            if($request->status==3){
                $datawd = ExternalTransfer::query()->with('contracts', 'gear')->where('status',$request->status)->where('clieaner_can_time','>',now())->get();
            }else{
                $datawd = ExternalTransfer::query()->with('contracts', 'gear')->where('status',$request->status)->get();
            }
        }
        $dscwd = ExternalTransfer::query()->where('status',1)->count();
        $dqcwd = ExternalTransfer::query()->where('status',2)->count();
        $dqxwd = ExternalTransfer::query()->where('status',3)->where('clieaner_can_time','>',now())->count();
        return $this->success(compact('data','dsc','dqc','dqs','dqx','datawd','dscwd','dqcwd','dqxwd'));
    }
    //设置未结清状态
    public function unclearedStatus(CarOrder $model,Request $request){
        $order = $model->find($request->order_id);
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        $order->uncleared_status = $request->uncleared_status;
        $order->save();
        return $this->success('更新成功');
    }
    // 月租订单对账功能
    public function orderMonthDz(CarOrder $model,Request $request){
        $data = $model->where('order_sn',$request->order_sn)->first();
        if(!$data){
            return $this->failed('订单不存在',201);
        }
        $pre_fetch_time_dz = now();
        // 修改当前订单为已结算已对账
        $data->status=6;
        $data->process_status=6;
        $data->is_reconciliation=2;
        $data->return_time=$pre_fetch_time_dz;
        $data->lease_days = 30;
        $data->fetch_hours = 0;
        $data->save();
        // 创建新的周期订单
        $adddata = $data->toArray();
        unset($adddata['id']);
        $adddata['order_sn'] = $this->getSn();
        $adddata['with_orders'] = $request->order_sn;
        $adddata['status'] = 5;
        $adddata['process_status'] = 2;
        $adddata['is_reconciliation'] = 1;
        $adddata['pre_fetch_time'] = $pre_fetch_time_dz;
        $adddata['fetch_time'] = $pre_fetch_time_dz;
        $adddata['pre_lease_days'] = $this->diffDaysDz($pre_fetch_time_dz, $data->pre_return_time);
        $adddata['pre_hours'] = $this->diffDaysDzHour($pre_fetch_time_dz, $data->pre_return_time);
        DB::table('car_orders')->insert($adddata);
        info('月租订单对账功能-创建新的周期订单：'.json_encode($adddata));
        return $this->success('更新成功');
    }
    // 长租结算功能
    // 长租订单结算，通过手机端【用车中】列表操作。点击续租，跳选两个选项，“临时续租”及“长租结算”，点击临时续租就是之前续租功能，可发送电子合同；点击长租结算，
    // 1是选择结算到×号（只可修改续租结算到几号，不可修改新建订单时取车时间），
    // 2是选择续租到×号，完成选择后有确定按键，确定后复制该订单到待结算列表可参与正常结算流程，
    // 此时原始订单还在在租列表中，打上长租订单的标签，订单显示出历史已结算过的租期，结算几次均显示。新的租期显示之前结算到×号为取车时间，续租到×号为还车时间（可继续操作续租功能）。
    // 点击长租结算这里，增加一个3输入公里数，关联到保养公里数那里
    public function orderMonthSett(CarOrder $model,Request $request){
        $data = $model->where('order_sn',$request->order_sn)->first();
        if(!$data){
            return $this->failed('订单不存在',201);
        }
        // 复制该订单到待结算列表可参与正常结算流程
        $addsn = $this->getSn();
        $adddata = $data->toArray();
        unset($adddata['id']);
        $adddata['order_sn'] = $addsn;
        $adddata['status'] = 6;
        $adddata['process_status'] = 3;
        $adddata['with_settorders'] = $request->order_sn;
        $adddata['is_reconciliation'] = 1;
        $adddata['return_time'] = $request->end_time;
        $adddata['lease_days'] = $this->diffDaysDz($data->pre_fetch_time, $request->end_time);
        $adddata['fetch_hours'] = $this->diffDaysDzHour($data->pre_fetch_time, $request->end_time);
        $adddata['send_car_photo'] = json_encode($data->send_car_photo);
        $adddata['outset_photo'] = json_encode($data->outset_photo);
        $adddata['return_photo'] = json_encode($data->return_photo);
        $adddata['scratch_images'] = json_encode($data->scratch_images);
        // info($adddata);
        if($request->filled('renturn_kilometer_num')){
            $adddata['renturn_kilometer_num'] = $request->renturn_kilometer_num;
            $data->renturn_kilometer_num = $request->renturn_kilometer_num;
        }
        DB::table('car_orders')->insert($adddata);
        info('长租结算功能-复制该订单到待结算列表可参与正常结算流程：'.json_encode($adddata));

        if(empty($data->with_orders)){
            $data->with_orders = $addsn;
        }else{
            $data->with_orders = $data->with_orders.','.$addsn;
        }
        $data->fetch_time = $request->end_time;
        $data->pre_fetch_time = $request->end_time;
        $data->pre_return_time = $request->xuzu_time;
        $data->pre_lease_days = $this->diffDaysDz($request->end_time, $request->xuzu_time);
        $data->pre_hours = $this->diffDaysDzHour($request->end_time, $request->xuzu_time);
        $data->save();
        return $this->success('更新成功');
        // return $this->failed('正在测试',201);
    }
    // 订单入账单
    public function orderEntry(Request $request){
        $is_wd = $request->is_wd;
        $is_month = $request->is_month;
        $order_sns = $request->order_sns;
        // 更新原订单状态为待入账
        if($is_month==0){
            if($is_wd == 2){
                ExternalTransfer::query()->whereIn('order_sn', $order_sns)->update(['is_reconciliation'=>2,'is_reconciliation_time'=>now()]);
            }else{
                CarOrder::query()->whereIn('order_sn', $order_sns)->update(['is_reconciliation'=>2,'is_reconciliation_time'=>now()]);
            }
        }
        // 外调车单入账
        $nowtime = now();
        $adddata = [];
        $adddata['order_sn'] = $this->getRSn();
        $adddata['status'] = 2;
        $adddata['operator'] = $request->operator??'';
        $adddata['department'] = $request->department??1;
        $adddata['created_at'] = $nowtime;
        $adddata['updated_at'] = $nowtime;
        $adddata['add_at'] = $nowtime;
        $adddata['remark'] = $request->remark??null;
        $adddata['total_money'] = $request->total_money??'0.00';
        $adddata['is_wd'] = $request->is_wd??1;
        $adddata['with_order'] = json_encode($order_sns);
        DB::table('entrymanages')->insert($adddata);
        return $this->success('对账成功');
    }
    private function diffDaysDz($start, $end)
    {
        $days = Carbon::parse($start)->diffInDays(Carbon::parse($end));
        $second = $this->diffSeconds($end, $start);
        if($second<3600 * 6){
            return 1;
        }else{
            $day = 3600 * 24 * $days;
            $second = $second - $day;
            if ($second >= 3600 * 6) {
                return $days + 1;
            }else {
                return $days;
            }

        }

    }
    private function diffDaysDzHour($start, $end)
    {
        $days = Carbon::parse($start)->diffInDays(Carbon::parse($end));
        $second = $this->diffSeconds($end, $start);
        if($second<3600 * 6){
            return 0;
        }else{
            $day = 3600 * 24 * $days;
            $second = $second - $day;
            if ($second >= 3600 * 6) {
                return 0;
            }else {
                $this->days = $days;
                $last_time = ceil($second / 3600);
                return $last_time;
            }
        }

    }
    //设置订单号
    private function getSn(){
        $car = CarOrder::query()
            ->select('id')
            ->where('id','>',0)
            ->orderByDesc('id')
            ->first();
        if($car){
            $num = $car->id+1;
        }else{
            $num = 1;
        }
        return date('Ymd',time()).$num;
    }
    //设置入账订单号
    private function getRSn(){
        $car = Entrymanage::query()
            ->select('id')
            ->where('id','>',0)
            ->orderByDesc('id')
            ->first();
        if($car){
            $num = $car->id+1;
        }else{
            $num = 1;
        }
        return 'rzd'.date('Ymd',time()).$num;
    }
    //更新任选字段
    public function updateAll(CarOrder $model,Request $request){
        $data = $model->where('order_sn',$request->order_sn);
        if(!$data){
            return $this->failed('订单不存在',201);
        }
        // 待送车和待清洗接单需要判断是否已被接口
        if($request->filled('send_employer_id')){
            $order = $data->first();
            if($order->send_employer_id!=0){
                return $this->failed('订单已被接单',201);
            }
        }
        // 待送车和待清洗接单需要判断是否已被接口
        if($request->filled('return_employer_id')){
            $order = $data->first();
            if($order->return_employer_id!=0){
                return $this->failed('订单已被接单',201);
            }
        }
        if($request->filled('clieaner_id')){
            $order = $data->first();
            if($order->clieaner_id!=0){
                return $this->failed('订单已被接单',201);
            }
        }
        // 取车。送车，清洗，如果已经操作了，直接忽略
        // 如果是发送待送车待取车待清洗，需要发送给车管员通知消息
        if($request->filled('is_send_order') && $request->is_send_order==2){
            $order = $data->first();
            if($order->is_send_order==2){
                return $this->success('修改成功');
            }
            $msg = [
                'plate_number'=>$request->plate_number??'',
                'title'=>'车辆送车单',
                'status'=>'待接单',
            ];
            $this->sendMsgByCgyUser($msg);
        }
        if($request->filled('is_send_return_order') && $request->is_send_return_order==2){
            $order = $data->first();
            if($order->is_send_return_order==2){
                return $this->success('修改成功');
            }
            $msg = [
                'plate_number'=>$request->plate_number??'',
                'title'=>'车辆取车单',
                'status'=>'待接单',
            ];
            $this->sendMsgByCgyUser($msg);
        }
        if($request->filled('is_send_clear_order') && $request->is_send_clear_order==2){
            $order = $data->first();
            if($order->is_send_clear_order==2){
                return $this->success('修改成功');
            }
            // $msg = [
            //     'plate_number'=>$request->plate_number??'',
            //     'title'=>'车辆清洗单',
            //     'status'=>'待接单',
            // ];
            $this->sendMsgByCgyUser($msg);
        }
        $data->update($request->all());
        return $this->success('修改成功');
    }
    // 给车管员发送模板消息
    private function sendMsgByCgyUser($msgs){
        $wechat_openidarr = Manager::query()->where('post_id',3)->pluck('wechat_openid');
        foreach($wechat_openidarr as $openid){
            if (!empty($openid)) {
                $msg = [
                    'openid'=>$openid,
                    'plate_number'=>$msgs['plate_number'],
                    'title'=>$msgs['title'],
                    'status'=>$msgs['status'],
                    'page'=>'pages/admin/sqc/sqc', // 发布的时候加上
                ];
                (new SendTemplateController())->sendTemplateSqc($msg);
                info(json_encode($msg));
            }
        }
    }
    //首页统计
    public function dashboard(CarOrder $model,Request $request){

        $user = $request->user();
        $size = $request->input('size',20);
        if($request->filled('order_sn')){
            $model = $model->where('order_sn','like','%'.$request->order_sn.'%');
        }
        if($request->filled('plate_number')){
            $model = $model->where('plate_number','like','%'.$request->plate_number.'%');
        }
        if($request->filled('department')){
            $model = $model->where('department',$request->department);
        }
//        if(!$request->all){
//            $model = $model->where('department',$user->department);
//        }
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
        $model = $model->where('status',Constant::ORDER_CLOSED)
            ->where('process_status',Constant::HISTORY_ORDER);
        if($request->type=='export'){
            $data = $model
                ->select('created_at','department','wx_name','order_operator','true_get_online_lease_price','true_get_off_lease_price','order_sn','plate_number')
                ->get();
            $list = [];
            foreach ($data as $k=>$v){
                $list[$k]['careated_at'] = date('Ymd',strtotime($v->created_at))??'';
                $list[$k]['department'] = $this->getDepartment($v->department);
                $list[$k]['wx_name'] = $v->order_operator;
                $list[$k]['true_get_online_lease_price'] = $v->true_get_online_lease_price??0;
                $list[$k]['true_get_off_lease_price'] = $v->true_get_off_lease_price??0;
                $total = $v->true_get_online_lease_price+$v->true_get_off_lease_price;
                if($total>0){
                    $list[$k]['total'] = $total;
                }else{
                    $list[$k]['total'] = '0.00';
                }
                $list[$k]['order_num'] = $v->order_sn;
                $list[$k]['plate_number'] = $v->plate_number;
            }

            $count = $data->count();
            $header = [
                '日期','门店','订单类型','线上租金','线下租金','实收租金','订单号','车牌号'
            ];
            return Excel::download(new OnTheJobExport($list,$header,$count),'订单数据.xlsx');
        }
        $online = $this->online($model);
        $offline = $this->offline($model);

        $data = $model
            ->select('created_at','department','wx_name','source','true_get_online_lease_price','true_get_off_lease_price','order_sn','plate_number')
            ->paginate($size);
        return $this->success(compact('data','online','offline'));

    }
    protected function online($model){
        $data = clone $model;
        return $data->sum('true_get_online_lease_price');
    }
    protected function offline($model){
        $data = clone $model;
        return $data->sum('true_get_off_lease_price');
    }
    //获取部门
    protected function getDepartment($num){
        switch ($num){
            case 1:
                return '总店';
                break;
            case 2:
                return '途安店';
                break;
            case 3:
                return '贝村店';
                break;
            case 4:
                return '柳青店';
                break;
            default:
                return '总店';
        }
    }

}
